package com.common.app.utls

import android.text.TextUtils
import android.util.Base64
import java.io.UnsupportedEncodingException
import java.nio.charset.StandardCharsets
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.IllegalBlockSizeException
import javax.crypto.KeyGenerator
import javax.crypto.NoSuchPaddingException
import javax.crypto.spec.IvParameterSpec
import javax.crypto.spec.SecretKeySpec

object AesUtils {

    const val encryptKey = "ztAtqrsGCPf2qDTW"
    const val encryptIv = "e5V8nhM72zAxXFcS"
    private const val algorithmstrECB = "AES/ECB/PKCS5Padding"
    private const val algorithmstrCBC = "AES/CBC/PKCS7Padding"

    fun encode(content: String): String {
        val kgen = KeyGenerator.getInstance("AES")
        kgen.init(128) //密钥长度 128
        val cipher = Cipher.getInstance(algorithmstrCBC)
        cipher.init(
            Cipher.ENCRYPT_MODE,
            SecretKeySpec(encryptKey.toByteArray(), "AES"),
            IvParameterSpec(encryptIv.toByteArray())
        )
        val bytes = cipher.doFinal(content.toByteArray(StandardCharsets.UTF_8))
        return Base64.encodeToString(bytes, Base64.NO_WRAP)
    }

    /**
     * 加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码
     * @return
     */
    fun encrypt(content: String, password: String): String {
        if (TextUtils.isEmpty(password)) {
            return ""
        }
        try {
//            SecretKeySpec key = new SecretKeySpec(Arrays.copyOf(password.getBytes("utf-8"), 16), "AES");
            val key =
                SecretKeySpec(password.toByteArray(), "AES")
            val cipher =
                Cipher.getInstance("AES/CBC/PKCS5Padding")
            val byteContent = content.toByteArray(charset("utf-8"))
            cipher.init(
                Cipher.ENCRYPT_MODE,
                key,
                IvParameterSpec(encryptIv.toByteArray())
            )
            return Base64.encodeToString(cipher.doFinal(byteContent), Base64.NO_WRAP) // 加密
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        } catch (e: NoSuchPaddingException) {
            e.printStackTrace()
        } catch (e: InvalidKeyException) {
            e.printStackTrace()
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        } catch (e: IllegalBlockSizeException) {
            e.printStackTrace()
        } catch (e: BadPaddingException) {
            e.printStackTrace()
        } catch (e: InvalidAlgorithmParameterException) {
            e.printStackTrace()
        }
        return ""
    }

    /**
     * 解密
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @return
     */
    fun decrypt(content: ByteArray?, password: String): ByteArray? {
        try {
//            SecretKeySpec key = new SecretKeySpec(Arrays.copyOf(password.getBytes("utf-8"), 16), "AES");
            val key =
                SecretKeySpec(password.toByteArray(), "AES")
            val cipher =
                Cipher.getInstance(algorithmstrCBC)
            cipher.init(
                Cipher.DECRYPT_MODE,
                key,
                IvParameterSpec(encryptIv.toByteArray())
            )
            return cipher.doFinal(content) // 加密
        } catch (e: NoSuchAlgorithmException) {
            e.printStackTrace()
        } catch (e: NoSuchPaddingException) {
            e.printStackTrace()
        } catch (e: InvalidKeyException) {
            e.printStackTrace()
        } catch (e: IllegalBlockSizeException) {
            e.printStackTrace()
        } catch (e: BadPaddingException) {
            e.printStackTrace()
        } //        catch (UnsupportedEncodingException e) {
        //            e.printStackTrace();
        //        }
        catch (e: InvalidAlgorithmParameterException) {
            e.printStackTrace()
        }
        return null
    }

    fun decode2String(content: String?, key: String?): String {
        if (content.isNullOrEmpty()) return ""
        if (key.isNullOrEmpty()) return ""
        //解密返回的数据
        val bytedata: ByteArray = Base64.decode(content,3) ?: return ""
        val afterdecrypt: ByteArray? = decrypt(bytedata, key)
        var result = "UnsupportedEncodingException"
        if (afterdecrypt == null) {
            return ""
        }
        if (afterdecrypt.size == 0) {
            return ""
        }
        try {
            result = String(afterdecrypt, StandardCharsets.UTF_8)
        } catch (e: UnsupportedEncodingException) {
            e.printStackTrace()
        }
        return result
    }

    fun encode2String(content: String, key: String): String? {
        if (TextUtils.isEmpty(key)) {
            return ""
        }
        return encrypt(content, key)
    }
}